package site.teamo.biu.net.client.mapper;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import site.teamo.biu.net.client.entity.ConnectionRuleDO;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author haocongshun
 * @date 2023/03/01 17:01:54
 */
@Mapper
@Component
public interface ConnectionRuleMapper extends BaseMapper<ConnectionRuleDO> {

    default void insertNotExists(List<ConnectionRuleDO> list) {
        Set<String> existsIds = this.selectList(new QueryWrapper<>())
                .stream()
                .map(ConnectionRuleDO::getId)
                .collect(Collectors.toSet());
        list.stream()
                .filter(e -> !existsIds.contains(e.getId()))
                .forEach(this::insert);
    }

    default boolean upsert(ConnectionRuleDO connectionRuleDO) {
        if (StrUtil.isBlank(connectionRuleDO.getId())) {
            return this.insert(connectionRuleDO) > 0;
        } else {
            return this.updateById(connectionRuleDO) > 0;
        }
    }

}
